import axios, { AxiosError, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from "axios";

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_API_BASEURL,
  timeout:5000
})

interface BaseResponse<T = any> {
  code: number | string;
  data: T;
  message: string;
  success: boolean;
}



// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    config.headers.icode = 'helloqianduanxunlianying'
    const token = localStorage.getItem("token");
    if (token) {
      // 如果token存在 注入token
      config.headers.Authorization = `Bearer ${token}`
    }
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.status !== 200) {
      return Promise.reject(new Error(`Error: ${response.status}`));
    }
    return response;
  },
  (error: any) => {
    const { response } = error;
    if (response) {
      return Promise.reject(response.data);
    }
  }
);


const requestInstance = <T = any>(config: AxiosRequestConfig): Promise<T> => {
  const conf = config;
  return new Promise((resolve, reject) => {
    service
      .request<any, AxiosResponse<BaseResponse>>(conf)
      .then((response: AxiosResponse<BaseResponse>) => {
        const data = response.data;
        if (data.code != 200 || !data.success) {
          reject(data.message);
        } else {
          resolve(data.data as T);
        }
        
      });
  });
};

export function get<T = any, U = any>(config: AxiosRequestConfig, url: string, parms?: U): Promise<T> {
  return requestInstance({ ...config, url, method: 'GET', params: parms });
}

export function post<T = any, U = any>(config: AxiosRequestConfig, url: string, data: U): Promise<T> {
  return requestInstance({ ...config, url, method: 'POST', data: data });
}

export function put<T = any, U = any>(config: AxiosRequestConfig, url: string, parms?: U): Promise<T> {
  return requestInstance({ ...config, url, method: 'PUT', params: parms });
}

export function del<T = any, U = any>(config: AxiosRequestConfig, url: string, data: U): Promise<T> {
  return requestInstance({ ...config, url, method: 'DELETE', data: data });
}

export function patch<T = any, U = any>(config: AxiosRequestConfig, url: string, data: U): Promise<T> {
  return requestInstance({ ...config, url, method: 'PATCH', data: data });
}
